package com.tt.job.zookeeper;

import com.tt.job.api.schedule.JobSchedule;
import com.tt.job.register.ScheduleChangeListener;
import com.tt.job.util.JobUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZookeeperScheduleChangeExecutor implements PathChildrenCacheListener {
    private final static Logger logger = LoggerFactory.getLogger(ZookeeperScheduleChangeExecutor.class);

    private final ScheduleChangeListener listener;

    public ZookeeperScheduleChangeExecutor(ScheduleChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        if (event.getData() == null) {
            return;
        }
        String path = event.getData().getPath();
        path = path.substring(path.lastIndexOf('/') + 1);
        String[] scheduleInfos = path.split("-");
        switch (event.getType()) {
            case CHILD_ADDED:
                //job节点添加
                if (scheduleInfos.length != 3) {
                    logger.warn("zookeeper schedule path is error. path:{}", path);
                    return;
                }
                String type = scheduleInfos[0];
                JobSchedule schedule = JobUtils.getScheduleInstance(type, event.getData().getData());
                if (schedule != null) {
                    listener.notifyScheduleAdded(schedule);
                } else {
                    logger.warn("zookeeper notify add schedule info is null");
                }
                break;
            case CHILD_REMOVED:
                if (scheduleInfos.length != 3) {
                    logger.warn("zookeeper schedule path is error. path:{}", path);
                    return;
                }
                type = scheduleInfos[0];
                schedule = JobUtils.getScheduleInstance(type, event.getData().getData());
                listener.notifyScheduleDeleted(schedule);
                break;
            case CHILD_UPDATED:
                if (scheduleInfos.length != 3) {
                    logger.warn("zookeeper schedule path is error. path:{}", path);
                    return;
                }
                type = scheduleInfos[0];
                schedule = JobUtils.getScheduleInstance(type, event.getData().getData());
                if (schedule != null) {
                    listener.notifyScheduleChanged(schedule);
                } else {
                    logger.warn("zookeeper notify update schedule info is null");
                }
                break;
        }
    }
}
